package com.server.modules.sys.zbus;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.validation.ConstraintViolationException;

import org.apache.commons.collections.map.HashedMap;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import org.nutz.json.Json;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;
import org.zbus.broker.Broker;
import org.zbus.broker.ZbusBroker;
import org.zbus.mq.Consumer;
import org.zbus.mq.Producer;
import org.zbus.mq.Consumer.ConsumerHandler;
import org.zbus.net.http.Message;

import com.alibaba.fastjson.JSON;
import com.monitorjbl.xlsx.StreamingReader;
import com.server.common.beanvalidator.BeanValidators;
import com.server.common.utils.StringUtils;
import com.server.common.utils.excel.ImportExcel;
import com.server.modules.sys.common.StaticDefine;
import com.server.modules.sys.dao.customer.impt.CustomerImportDao;
import com.server.modules.sys.dao.customer.impt.CustomerImportLogDao;
import com.server.modules.sys.entity.customer.impt.CustomerImport;
import com.server.modules.sys.entity.customer.impt.CustomerImportLog;
import com.server.modules.sys.service.batchno.BatchNoService;
import com.server.modules.sys.service.customer.impt.CustomerImportLogService;
import com.server.modules.sys.service.customer.impt.CustomerImportService;
import com.server.modules.sys.utils.Md5Utils;
import com.server.modules.sys.utils.RegexUtils;
import com.server.modules.sys.vo.ImportTempObj;
@Component
public class ProducerUtils implements IProducerUtilsService{
	@Resource
	private CustomerImportService customerImportService;
	@Resource
	private CustomerImportLogService customerImportLogService;
	@Resource
	private CustomerImportLogDao customerImportLogDao;
	@Resource
	private BatchNoService batchNoService;
	public  void produceAnalyzeExcelFile(File file,String mqName) throws IOException, InterruptedException  {
		try {
			
			ImportTempObj obj=new ImportTempObj();
			analyzeFile(file, obj);
			//Broker broker = new ZbusBroker("http://101.201.82.116:15555/");
			Broker broker = new ZbusBroker("127.0.0.1:15555");
			Producer producer = new Producer(broker,  mqName);
			System.out.println("解析excel队列启动：");
		if(!CollectionUtils.isEmpty(obj.getBigList())){
				List<List<CustomerImport>> bigList = obj.getBigList();
				for (List<CustomerImport> list : bigList) {
					producer.createMQ();
					Message msg = new Message();
					obj.setFile(file);
					obj.setList(list);
					obj.setBigList(null);
					msg.setBody(JSON.toJSONString(obj));
					msg = producer.sendSync(msg);
				}
			}else{
				producer.createMQ();
				Message msg = new Message();
				obj.setFile(file);
				msg.setBody(JSON.toJSONString(obj));
				msg = producer.sendSync(msg);
			}
			broker.close();
			
			
		} catch (Exception e) {
			e.printStackTrace();
		} 
	}
	private void analyzeFile(File file, ImportTempObj obj)
			throws InvalidFormatException, IOException, InstantiationException,
			IllegalAccessException {
		CustomerImportLog customerImportLog=new CustomerImportLog();
		Map<String, Object> ret = new HashMap<String, Object>();
		int successNum = 0;
		int failureNum = 0;
		StringBuilder failureMsg = new StringBuilder();
		String fileName = file.getName();
		Long begin1 = new Date().getTime();
		InputStream is =  new FileInputStream(file);
		Workbook wb = null;
		if (org.apache.commons.lang3.StringUtils.isBlank(fileName)){
			throw new RuntimeException("导入文档为空!");
		}else if(fileName.toLowerCase().endsWith("xls")){
			wb = new HSSFWorkbook(is);
		}else if(fileName.toLowerCase().endsWith("xlsx")){
			wb = StreamingReader.builder()
					.rowCacheSize(100)    // number of rows to keep in memory (defaults to 10)
					.bufferSize(4096)     // buffer size to use when reading InputStream to file (defaults to 1024)
					.open(is);
		}else{
			wb = new HSSFWorkbook(is);
			throw new RuntimeException("文档格式不正确!");
		}
		List<CustomerImport> list=new ArrayList<>();
		String type=customerImportService.Excel2Data(list, wb);
		// 插入日志
		customerImportLog.setType(type);
		// 入库
		String batchNO = batchNoService.getBatchNO("1");
		customerImportLog.setBatchNo(batchNO);
		String fileMD5 = Md5Utils.getFileMD5(file);
		int countByMd5 = customerImportLogService.countByMd5(fileMD5);
		 //之前上传过
		 if(countByMd5>0){
			 	failureMsg.append("<br/>导入失败：您上传的文件【" + fileName+ "】已经上传过，请不要重复上传哦");
				ret.put("failureMsg", failureMsg);
				ret.put("successNum", successNum);
				ret.put("failureNum", failureNum);
				 customerImportLog.preInsert();
				customerImportLog.setExpectCount(list.size() + "");
				customerImportLog.setValidCount(successNum + "");
				customerImportLog.setRemarks("【系统自动导入】：导入失败：文件【" + fileName+ "】已经上传过");
				obj.setFailureNum(failureNum);
				obj.setFailureMsg(failureMsg);
				customerImportLog.setIsNewRecord(false);
				customerImportLogDao.insert(customerImportLog);
			 return;
		 }else{
		     customerImportLog.setMd5(fileMD5);
			 customerImportLog.setFilename(file.getName());
			 customerImportLog.setFilesize(file.length()+"");
			 customerImportLog.setFileurl(file.getPath());
		 }
		List<CustomerImport> listValid = new ArrayList<CustomerImport>();// 校验后有效的
		failureNum = customerImportService.validateData(failureNum, failureMsg, listValid, list);
		obj.setFailureNum(failureNum);
		obj.setFailureMsg(failureMsg);
		List<List<CustomerImport>> bigList = obj.getBigList();
		if(listValid.size()>10000){
			int size=listValid.size();
			double ceil = Math.ceil((double) size / (double) 10000);
			int group=(int)ceil;
			int k=0;
			for (int i = 0; i < group; i++) {
				if(k+10000<size){
					obj.getBigList().add(listValid.subList(k, k+10000));
				}else{
					obj.getBigList().add(listValid.subList(k,size));
				}
				k+=10000;
			}
		}
		obj.setExpectCount(list.size());
		obj.setList(listValid);
		obj.setLog(customerImportLog);
		long end=System.currentTimeMillis();
		System.out.println("读文件操作cast:" + (end - begin1) / 1000F + "s");
	}
	
	
	
	
	
	
	
	
}
